﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Xml;
using System.Xml.Schema;
using System.IO;

namespace ConsoleApplication1
{
    class XMLValidator
    {
        private String fileName;
        static private ArrayList errors = new ArrayList();
        static private bool bValid;

        //constractor
        public XMLValidator(String fileName)
        {
            this.fileName = fileName;
            bValid = true;
        }

        //contains all the errors found in doc
        public ArrayList GetErrors()
        {
            return errors;
        }

        //validates if the doc is a valid XML file
        public bool Validate()
        {
            XmlValidatingReader reader = null;
            try
            {
                errors.Clear();
                bValid = true;
                XmlTextReader txtreader = new XmlTextReader(fileName);
                reader = new XmlValidatingReader(txtreader);

                // Set the validation event handler
                reader.ValidationEventHandler +=
                       new ValidationEventHandler(ValidationCallBack);

                // Read XML data
                while (reader.Read()) { }

            }
            catch (Exception e)
            {
                bValid = false;
                errors.Add(e.Message);
            }
            finally
            {
                //Close the reader.
                reader.Close();
            }

            return bValid;
        }

        //adds a new error that was found
        private void ValidationCallBack(object sender, ValidationEventArgs args)
        {
            bValid = false;
            errors.Add(args.Message);
        }

        // if the file was found invalid, fixing the file to be a valid XML
        public void FixFile(string fileName)
        {
            string current_path = Directory.GetParent(Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory()).ToString()).ToString()).ToString();
            char[] buffer = new char[10000];
            string renamedFile = fileName + ".orig";
            File.Move(fileName, renamedFile);
            using (StreamReader sr = new StreamReader(renamedFile))
            using (StreamWriter sw = new StreamWriter(fileName, false))
            {
                sw.Write("<XML>");
                int read;
                while ((read = sr.Read(buffer, 0, buffer.Length)) > 0)
                    sw.Write(buffer, 0, read); sw.Write("</XML>");
            }
            File.Delete(renamedFile);
        }


    }
}
